import axios from "axios";
import qs from "qs";
import type {AxiosInstance, AxiosRequestConfig, AxiosResponse} from "axios"
import { showMessage } from "./status";
import JsEncrypt from 'jsencrypt'
import {Base64} from 'js-base64'


//生成Token
const genToken = ():any =>{
    let token:any = localStorage.getItem("token");
    let oToken =token ? JSON.parse(token) : '';
    if(!oToken || !oToken.t || !oToken.e || (oToken.e + 2592000000 < new Date().getTime())){
        return '';
    }
    let publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxwFju5VsN5E61YPjL/qD04hvqulhOxIzxWH2ZvSXZz/XY1xmwzq3avl3sKE6/rYMvTXMwULtMUaFRhvpsFFlmXHK0dOZ1/q7ruH1/sBT0Kx8aQafa5v02V4ARlR3hs85eznVWUfAW3EyGva+2uCVn869PtQfsf5ihdRT+FYGUBwIDAQAB';
    let encrypt = new JsEncrypt();
        encrypt.setPublicKey(
            //KEY RSA公钥
            publicKey
        );

    let rsa = encrypt.encrypt(JSON.stringify({uid:localStorage.getItem('uid'),timeStamp:Math.round(new Date().getTime() / 1000)}));
    return Base64.encode(JSON.stringify({r:rsa,t:oToken.t,s: 'ios'}));
}

let axiosInstance:AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_URL,
    headers: {
        Accept: "application/json",
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8;",
        'Token': genToken()
    },
    transformRequest: [
        function(data, headers: any) {
            headers['Token'] = genToken();
            if (!(data instanceof FormData)) data = qs.stringify(data);
            return data;
        }
    ]
});



// axios实例拦截响应
axiosInstance.interceptors.response.use(
    (response: AxiosResponse) => {
        // if (response.headers.authorization) {
        //     localStorage.setItem('token', response.headers.authorization);
        // } else {
        //     if (response.data && response.data.token) {
        //         localStorage.setItem('token', response.data.token);
        //     }
        // }
        if (response.data && response.data.token) {
            localStorage.setItem('token', response.data.token);
        }
        if (response.status === 200) {
            let {data} = response;
            return data;
        } else {
            showMessage(response.status)
            return response;
        }
    },
    // 请求失败
    (error: any) => {
        const {response} = error;
        if (response) {
            // 请求已发出，但是不在2xx的范围
            showMessage(response.status)
            return Promise.reject(response.data);
        } else {
            console.log('网络连接异常,请稍后再试!');
        }
    }
);

// axios实例拦截请求
axiosInstance.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        return config;
    },
    (error: any) => {
        return Promise.reject(error);
    }
)


export default axiosInstance